package xin.petstore.framework.orm.mybatis.paginator.dialect;

import xin.petstore.framework.orm.mybatis.paginator.domain.PageBounds;
import org.apache.ibatis.mapping.MappedStatement;

public class SQLServerDialect extends Dialect {
    public SQLServerDialect(MappedStatement mappedStatement, Object parameterObject, PageBounds pageBounds) {
        super(mappedStatement, parameterObject, pageBounds);
    }

    static int getAfterSelectInsertPoint(String sql) {
        int selectIndex = sql.toLowerCase().indexOf("select");
        int selectDistinctIndex = sql.toLowerCase().indexOf("select distinct");
        return selectIndex + (selectDistinctIndex == selectIndex ? 15 : 6);
    }

    @Override
    protected String getLimitString(String sql, String offsetName, int offset, String limitName, int limit) {
        if (offset > 0) {
            throw new UnsupportedOperationException("sql server has no offset");
        }

        setPageParameter(limitName, Integer.valueOf(limit), Integer.class);
        return new StringBuffer(sql.length() + 8)
                .append(sql)
                .insert(getAfterSelectInsertPoint(sql), " top " + limit)
                .toString();
    }
}